package com.my.util;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class PackageUtil {
	
	private static final String suffix = ".class";
	
	// com.my
	public static void scan(String packagePath, Map<String, Object> ret) {
		
		String url = PackageUtil.class.getResource("").getPath();
		String name = PackageUtil.class.getPackage().getName().replaceAll("\\.", "/") + "/";
		String dir = url.substring(0, url.lastIndexOf(name));
		String path = dir + packagePath.replaceAll("\\.", "/");
		System.out.println(path);
		
		File root = new File(path);
		File[] files = root.listFiles();
		for(File file: files) {
			if(file.isFile()) {
				String fileName = file.getName();
				if(fileName.endsWith(suffix)) {
					fileName = fileName.substring(0, fileName.indexOf(suffix));
					try {
						Object obj = Class.forName(packagePath + "." + fileName).newInstance();
						ret.put(packagePath + "." + fileName, obj);
					} catch (ClassNotFoundException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (InstantiationException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			} else if(file.isDirectory()) {
				scan(file.getAbsolutePath(), ret);
			}
		}
		
	}
	
	public static void main(String[] args) {
		String url = PackageUtil.class.getResource("").getPath();
		String name = PackageUtil.class.getPackage().getName().replaceAll("\\.", "/") + "/";
		String dir = url.substring(0, url.lastIndexOf(name));
		System.out.println(url);
		System.out.println(name);
		System.out.println(dir);
		
		Map map = new HashMap();
		PackageUtil.scan("com.my.controller", map);
		System.out.println(map);

	}

}
